﻿using Kingdee.BOS;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace KingdeeWebServiceProject
{
    internal static class BatchHelper
    {
        #region 插入批次（充值批次、退款批次）      
        internal static void Insert2batch(BatchDataObject bdo, string batchType = "0")
        {
            long new_batch;
            if (bdo.BatchType == 0)
            {
                //充值批次
                //查询该卡的充值批次记录
                string strSql = string.Format(@"select * from Vv_Card_Batch where FCARDNO = '{0}' and FBATCHTYPE = '0' order by FBATCH desc ", bdo.cardNo);
                var ds = Data.XDDDBUtils.ExecuteDateSet(strSql);
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    new_batch = Convert.ToInt64(ds.Tables[0].Rows[0]["FBATCH"]) + 1;
                }
                else
                {
                    new_batch = 1;
                }
                //获取批次表的FID
                long FID = 0L;
                strSql = "EXEC CMK_PR_GetTableSequence @TableName = 'Vv_Card_Batch', @Count =  1";
                var Idrs = Data.XDDDBUtils.ExecuteDateSet(strSql);
                if (Idrs != null && Idrs.Tables.Count > 0 && Idrs.Tables[0].Rows.Count > 0)
                {
                    FID = Convert.ToInt64(Idrs.Tables[0].Rows[0]["Id"]);
                }
                //插入批次数据
                strSql = @"INSERT INTO Vv_Card_Batch (FID, FCARDNO,FBATCH,FBATCHTYPE,FRECHARGEDATE,FRECHARGETIME,FRECHARGEAMT,FGIVEAMT,FBELENCEAMT,FAMTTYPE,FLEFTAMT,FBATCHUSINGSTATUS,FTRANSSERIAL,FNOTE)
                VALUES(" + FID + ",'" + bdo.cardNo + "'," + new_batch + ",'" + bdo.BatchType.ToString() + "','" + bdo.rechargeDate + "','" + bdo.rechargeTime + "'," + bdo.rechargeAmt + "," + bdo.giveAmt + "," + bdo.belenceAmt + ",'" + bdo.AmtType + "'," + bdo.belenceAmt + ",'" + bdo.BatchUsingStatus.ToString() + "','" + bdo.TransSerial + "','" + bdo.Note + "'); ";
                Data.XDDDBUtils.Execute(strSql);
            }
            else if (bdo.BatchType == 1)
            {
                //退款批次
                //查询该卡的退款批次记录
                string strSql = string.Format(@"select * from Vv_Card_Batch_Refund where FCARDNO = '{0}' and FBATCHTYPE = '1' order by FBATCH desc ", bdo.cardNo);
                var ds = Data.XDDDBUtils.ExecuteDateSet(strSql);
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    new_batch = Convert.ToInt64(ds.Tables[0].Rows[0]["FBATCH"]) + 1;
                }
                else
                {
                    new_batch = 1;
                }
                //获取批次表的FID
                long FID = 0L;
                strSql = "EXEC CMK_PR_GetTableSequence @TableName = 'Vv_Card_Batch_Refund', @Count =  1";
                var Idrs = Data.XDDDBUtils.ExecuteDateSet(strSql);
                if (Idrs != null && Idrs.Tables.Count > 0 && Idrs.Tables[0].Rows.Count > 0)
                {
                    FID = Convert.ToInt64(Idrs.Tables[0].Rows[0]["Id"]);
                }
                //插入批次数据
                strSql = @"INSERT INTO Vv_Card_Batch_Refund (FID, FCARDNO,FBATCH,FBATCHTYPE,FRECHARGEDATE,FRECHARGETIME,FRECHARGEAMT,FGIVEAMT,FBELENCEAMT,FAMTTYPE,FLEFTAMT,FBATCHUSINGSTATUS,FTRANSSERIAL,FNOTE)
                VALUES(" + FID + ",'" + bdo.cardNo + "'," + new_batch + ",'" + bdo.BatchType.ToString() + "','" + bdo.rechargeDate + "','" + bdo.rechargeTime + "'," + bdo.rechargeAmt + "," + bdo.giveAmt + "," + bdo.belenceAmt + ",'" + bdo.AmtType + "'," + bdo.belenceAmt + ",'" + bdo.BatchUsingStatus.ToString() + "','" + bdo.TransSerial + "','" + bdo.Note + "'); ";
                Data.XDDDBUtils.Execute(strSql);
            }
        }
        #endregion

        #region 按批次扣减退款批次金额
        internal static int Reduce2batch(string cardNo, decimal operAmt, string TransSerial, int bantchType)
        {

            //查询这个卡号的充值批次记录   0 未扣减 1部分扣减 2扣减完成  
            //先扣退款批次，查询有没有退款批次
            string strSql = string.Format(@"select * from Vv_Card_Batch_Refund where FCARDNO = '{0}'and FBATCHTYPE = '" + bantchType.ToString() + "' and FBATCHUSINGSTATUS  <> '2'   order by FBATCH asc ", cardNo);
            var ds = Data.XDDDBUtils.ExecuteDateSet(strSql);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                //记录本次消费扣减了多少的本金，多少的赠金
                decimal FCapitalOperValue = 0M;  //扣减本金
                decimal FGrantOperValue = 0M; //扣减赠金

                //找到早的充值批次，判断当前批次的情况
                long id = Convert.ToInt64(ds.Tables[0].Rows[0]["FID"]);
                long batch = Convert.ToInt64(ds.Tables[0].Rows[0]["FBATCH"]);
                string amtType = Convert.ToString(ds.Tables[0].Rows[0]["FAMTTYPE"]);
                string batchUsingType = Convert.ToString(ds.Tables[0].Rows[0]["FBATCHUSINGSTATUS"]);
                decimal batchAmt = Convert.ToDecimal(ds.Tables[0].Rows[0]["FBELENCEAMT"]);
                decimal leftAmt = Convert.ToDecimal(ds.Tables[0].Rows[0]["FLEFTAMT"]);
                //判断当前批次是否满足消费金额大小，满足扣减，有超过则往下一个批次扣
                if (batchUsingType == "0" || batchUsingType == "1") //扣减
                {
                    if (leftAmt > operAmt) //满足扣减，更新为 1 后完成批次
                    {
                        leftAmt = leftAmt - operAmt;
                        FCapitalOperValue = (amtType == "0") ? operAmt : 0M;
                        FGrantOperValue = (amtType == "1") ? operAmt : 0M;
                        strSql = string.Format("update CMK_VIP_T_CardAction set FCapitalOperValue = FCapitalOperValue + {0},FGrantOperValue = FGrantOperValue + {1} where FTRANSSERIAL = '{2}'", FCapitalOperValue, FGrantOperValue, TransSerial);
                        Data.XDDDBUtils.Execute(strSql);
                        strSql = string.Format("update Vv_Card_Batch_Refund set FLEFTAMT = {0},FBATCHUSINGSTATUS = '1' where FID = {1}", leftAmt, id);
                        Data.XDDDBUtils.Execute(strSql);
                        return 1;
                    }
                    else //批次超额 更新本批次为 2 后递归
                    {
                        FCapitalOperValue = (amtType == "0") ? leftAmt : 0M;  //全扣完，直接把leftAmt赋值给FCapitalOperValue
                        FGrantOperValue = (amtType == "1") ? leftAmt : 0M;
                        strSql = string.Format("update CMK_VIP_T_CardAction set FCapitalOperValue = FCapitalOperValue + {0},FGrantOperValue = FGrantOperValue + {1} where FTRANSSERIAL = '{2}'", FCapitalOperValue, FGrantOperValue, TransSerial);
                        Data.XDDDBUtils.Execute(strSql);
                        strSql = string.Format("update Vv_Card_Batch_Refund set FLEFTAMT = 0.0,FBATCHUSINGSTATUS = '2' where FID = {0}", id);
                        Data.XDDDBUtils.Execute(strSql);
                        return Reduce2batch(cardNo, operAmt - leftAmt, TransSerial, 1);
                    }
                }
            }
            else
            {
                reduce2batch2(cardNo, operAmt, TransSerial, 0);
            }
            //更新卡资料对应的累计剩余本金和累计剩余赠金
            return 1;
        }

        //按批次扣减充值批次金额
        internal static int reduce2batch2(string cardNo, decimal operAmt, string TransSerial, int bantchType)
        {
            //查询这个卡号的充值批次记录   0 未扣减 1部分扣减 2扣减完成  
            //先扣退款批次，查询有没有退款批次
            string strSql = "";

            strSql = string.Format(@"select * from Vv_Card_Batch where FCARDNO = '{0}'and FBATCHTYPE = '" + bantchType.ToString() + "' and FBATCHUSINGSTATUS  <> '2'   order by FBATCH asc ", cardNo);
            var ds = Data.XDDDBUtils.ExecuteDateSet(strSql);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                //记录本次消费扣减了多少的本金，多少的赠金
                decimal FCapitalOperValue = 0M;  //扣减本金
                decimal FGrantOperValue = 0M; //扣减赠金

                //找到早的充值批次，判断当前批次的情况
                long id = Convert.ToInt64(ds.Tables[0].Rows[0]["FID"]);
                long batch = Convert.ToInt64(ds.Tables[0].Rows[0]["FBATCH"]);
                string amtType = Convert.ToString(ds.Tables[0].Rows[0]["FAMTTYPE"]);
                string batchUsingType = Convert.ToString(ds.Tables[0].Rows[0]["FBATCHUSINGSTATUS"]);
                decimal batchAmt = Convert.ToDecimal(ds.Tables[0].Rows[0]["FBELENCEAMT"]);
                decimal leftAmt = Convert.ToDecimal(ds.Tables[0].Rows[0]["FLEFTAMT"]);
                //判断当前批次是否满足消费金额大小，满足扣减，有超过则往下一个批次扣
                if (batchUsingType == "0" || batchUsingType == "1") //扣减
                {
                    if (leftAmt > operAmt) //满足扣减，更新为 1 后完成批次
                    {
                        leftAmt = leftAmt - operAmt;
                        FCapitalOperValue = (amtType == "0") ? operAmt : 0M;
                        FGrantOperValue = (amtType == "1") ? operAmt : 0M;
                        strSql = string.Format("update CMK_VIP_T_CardAction set FCapitalOperValue = FCapitalOperValue + {0},FGrantOperValue = FGrantOperValue + {1} where FTRANSSERIAL = '{2}'", FCapitalOperValue, FGrantOperValue, TransSerial);
                        Data.XDDDBUtils.Execute(strSql);
                        strSql = string.Format("update Vv_Card_Batch set FLEFTAMT = {0},FBATCHUSINGSTATUS = '1' where FID = {1}", leftAmt, id);
                        Data.XDDDBUtils.Execute(strSql);
                        return 1;
                    }
                    else //批次超额 更新本批次为 2 后递归
                    {
                        FCapitalOperValue = (amtType == "0") ? leftAmt : 0M;  //全扣完，直接把leftAmt赋值给FCapitalOperValue
                        FGrantOperValue = (amtType == "1") ? leftAmt : 0M;
                        strSql = string.Format("update CMK_VIP_T_CardAction set FCapitalOperValue = FCapitalOperValue + {0},FGrantOperValue = FGrantOperValue + {1} where FTRANSSERIAL = '{2}'", FCapitalOperValue, FGrantOperValue, TransSerial);
                        Data.XDDDBUtils.Execute(strSql);
                        strSql = string.Format("update Vv_Card_Batch set FLEFTAMT = 0.0,FBATCHUSINGSTATUS = '2' where FID = {0}", id);
                        Data.XDDDBUtils.Execute(strSql);
                        return Reduce2batch(cardNo, operAmt - leftAmt, TransSerial, 1);
                    }
                }
            }
            //更新卡资料对应的累计剩余本金和累计剩余赠金
            return 1;
        }
        #endregion

        #region 获取正向消费的扣减金额
        internal static void getAmtByTransSerial(string TransSerial, decimal OperValue, out decimal FCapitalOperValue, out decimal FGrantOperValue)
        {
            FCapitalOperValue = 0M;
            FGrantOperValue = 0M;
            //选择出对应交易的使用了多少本金和赠金  判断当前退款是部分退款还是整单退款
            string strSql = string.Format(@"select FCapitalOperValue,FGrantOperValue from CMK_VIP_T_CardAction where FTRANSSERIAL = '{0}' ", TransSerial);
            var ds = Data.XDDDBUtils.ExecuteDateSet(strSql);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                FCapitalOperValue = Convert.ToDecimal(ds.Tables[0].Rows[0]["FCapitalOperValue"]);
                FGrantOperValue = Convert.ToDecimal(ds.Tables[0].Rows[0]["FGrantOperValue"]);
                //判断当前金额是整单退还是部分退
                if (OperValue == (FCapitalOperValue + FGrantOperValue))
                {
                    //整单退  --修改原交易流水记录的金额字段
                    strSql = string.Format(@"update CMK_VIP_T_CardAction set FCapitalOperValue = 0.0,FGrantOperValue = 0.0 where FTRANSSERIAL = '{0}' ", TransSerial);
                    Data.XDDDBUtils.Execute(strSql);
                }
                else
                {
                    //部分退  先退赠金  再退本金
                    if (OperValue >= FGrantOperValue)
                    {
                        decimal new_FCapitalOperValue = FCapitalOperValue - OperValue - FGrantOperValue;
                        strSql = string.Format(@"update CMK_VIP_T_CardAction set FCapitalOperValue = {1},FGrantOperValue = 0.0 where FTRANSSERIAL = '{0}' ", TransSerial, new_FCapitalOperValue);
                        Data.XDDDBUtils.Execute(strSql);
                        FCapitalOperValue = OperValue - FGrantOperValue;
                    }
                    else if (OperValue < FGrantOperValue)
                    {
                        decimal new_FGrantOperValue = FGrantOperValue - OperValue;
                        strSql = string.Format(@"update CMK_VIP_T_CardAction set FGrantOperValue = {1} where FTRANSSERIAL = '{0}' ", TransSerial, new_FGrantOperValue);
                        Data.XDDDBUtils.Execute(strSql);
                        FGrantOperValue = FGrantOperValue - OperValue;
                    }
                }
            }
        }
        #endregion
    }
}
